package com.woniuxy.carlife.carlifeuserweb.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.woniuxy.carlife.carlifecommonsweb.exception.CarlifeGlobalException;
import com.woniuxy.carlife.carlifecommonsweb.responsetemplate.Result;
import com.woniuxy.carlife.carlifecommonsweb.responsetemplate.StatusCode;
import com.woniuxy.carlife.carlifecommonsweb.util.CopyUtil;
import com.woniuxy.carlife.carlifecommonsweb.util.JwtUtil;
import com.woniuxy.carlife.carlifeusermodel.dto.*;
import com.woniuxy.carlife.carlifeusermodel.param.CarinsuranceParam;
import com.woniuxy.carlife.carlifeusermodel.param.Usercarparam;
import com.woniuxy.carlife.carlifeuserweb.entity.*;
import com.woniuxy.carlife.carlifeuserweb.service.*;
import com.woniuxy.carlife.carlifeuserweb.util.StatusMessageEnum;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sun.rmi.runtime.Log;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author zjq
 * @ClassName:UsercarController
 * @Description:用户汽车表
 * @date 2021/4/6 20:02
 **/

@Slf4j
@RestController
@Api(tags = "用户汽车管理接口信息")//用于描述接口类的相关信息，作用于类上
@RequestMapping("/usercar")
public class UsercarController {

    @Resource
    UsercarService usercarService;

    @Resource
    MaintenanceService maintenanceService;

    //车险信息
    @Resource
    CarinsuranceService carinsuranceService;

    //汽车品牌
    @Resource
    CarbrandService carbrandService;
    //查询汽车型号
    @Resource
    CarmodelService carmodelService;

    //    汽车排量
    @Resource
    CardisplacementService cardisplacementService;

    //汽车年份
    @Resource
    CaryearsService caryearsService;


    /*
     * 功能描述〈用户查询所有的汽车〉
     * @author:zjq
     * @param:
     * @return:
     * @Date 2021/4/12 10:23
     * @throws
     */

    @ApiOperation(value = "用户查询所有的汽车,通过登录获取token中的userId")
    @GetMapping("/ordinary/findUsercarByUserId")
    public Result findUsercarByUserId() {
        ServletRequestAttributes sra =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = sra.getRequest().getHeader("token");
        JwtUtil jwtUtil = new JwtUtil();
        Claims claims = jwtUtil.parseTokenOrdinary(token);
        if (claims == null) {

            return new Result(false, StatusCode.NOT_LOGGED_IN, StatusMessageEnum.NOT_LOGGED_IN.toString());
        }
        Object o = claims.get("token");
        Integer tokenUserId = Integer.valueOf(String.valueOf(o));

        if (tokenUserId != null && tokenUserId != 0) {
            List<Usercar> usercarByUserId = usercarService.findUsercarByUserId(tokenUserId);

            List<UsercarDto> list = CopyUtil.getList(usercarByUserId, UsercarDto.class);
            return list != null ?
                    new Result(true, StatusCode.SEARCH_SUCCESSFUL, StatusMessageEnum.SEARCH_SUCCESSFUL.toString(), list)
                    : new Result(false, StatusCode.QUERY_IS_EMPTY, StatusMessageEnum.QUERY_IS_EMPTY.toString());

        }
        return new Result(false, StatusCode.CAN_NOT_BE_EMPTY, StatusMessageEnum.CAN_NOT_BE_EMPTY.toString());
    }


    /*
     * 功能描述〈用户查询单个汽车同时查询保养信息〉
     * @author:zjq
     * @param:
     * @return:
     * @Date 2021/4/12 10:23
     * @throws
     */
    @ApiOperation(value = "用户查询展示默认的单个汽车同时查询保养信息,通过登录获取token中的userId")
    @GetMapping("/ordinary/findUsercarByUserIdUsercarId")
    public Result findUsercarByUserIdUsercarId() {
        ServletRequestAttributes sra =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = sra.getRequest().getHeader("token");
        JwtUtil jwtUtil = new JwtUtil();
        Claims claims = jwtUtil.parseTokenOrdinary(token);
        if (claims == null) {

            return new Result(false, StatusCode.NOT_LOGGED_IN, StatusMessageEnum.NOT_LOGGED_IN.toString());
        }
        Object o = claims.get("token");
        Integer tokenUserId = Integer.valueOf(String.valueOf(o));

        if (tokenUserId != null && tokenUserId != 0) {
            log.info("开始查询用户查询展示默认的单个汽车");

//            查询单个汽车
            Usercar usercarByUserIdUsercarId = usercarService.findUsercarByUserIdUsercarId(tokenUserId);
            if (ObjectUtil.isNull(usercarByUserIdUsercarId)) {
                return new Result(false, StatusCode.QUERY_IS_EMPTY, StatusMessageEnum.QUERY_IS_EMPTY.toString());
            }
            UsercarDto one = CopyUtil.getOne(usercarByUserIdUsercarId, UsercarDto.class);
            log.info("开始查询用户查询展示默认的单个汽车结束");

//            查询汽车保养
            log.info("开始查询用户查询展示默认的单个汽车的查询汽车保养信息");
            Maintenance maintenance = maintenanceService.findfindMaintenanceByuserIdMaintenanceId(String.valueOf(usercarByUserIdUsercarId.getUsercarId()));
            BeanUtil.copyProperties(maintenance, one);

//            one = CopyUtil.getOne(maintenance, UsercarDto.class);
            Date maintenanceTime = one.getMaintenanceTime();
            log.info("开始查询用户查询展示默认的单个汽车的查询汽车保养信息结束");

//            下次保养时间
            log.info("开始计算下次保养时间");
            DateTime dateTime = DateUtil.offsetDay(maintenanceTime, 20);
            one.setMaintenanceTime(dateTime);
            log.info("开始计算下次保养时间结束");
            return one != null ?
                    new Result(true, StatusCode.OK, StatusMessageEnum.SUCCESSFULLY_MODIFIED.toString(), one)
                    : new Result(false, StatusCode.ERROR, StatusMessageEnum.FAIL_TO_EDIT.toString());

        }
        return new Result(false, StatusCode.ERROR, StatusMessageEnum.CAN_NOT_BE_EMPTY.toString());
    }

    /*
     * 功能描述〈用户新增汽车〉
     * @author:zjq
     * @param:
     * @return:
     * @Date 2021/4/12 20:38
     * @throws
     */

    //@ApiOperation用于描述接口方法，作用于方法上
    @ApiOperation(value = "用户新增汽车")
    @PostMapping("/ordinary/addUsercarByUserId")
    public Result addUsercarByUserId(@ApiParam Usercarparam usercarparam) {
        ServletRequestAttributes sra =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = sra.getRequest().getHeader("token");
        JwtUtil jwtUtil = new JwtUtil();
        Claims claims = jwtUtil.parseTokenOrdinary(token);
        if (claims == null) {

            return new Result(false, StatusCode.NOT_LOGGED_IN, StatusMessageEnum.NOT_LOGGED_IN.toString());
        }
        Object o = claims.get("token");
        Integer tokenUserId = Integer.valueOf(String.valueOf(o));

        Usercar one = CopyUtil.getOne(usercarparam, Usercar.class);
        one.setUserId(tokenUserId);

        log.info("开始执行用户新增汽车");
        boolean b = usercarService.addUsercarByUserId(one);
        log.info("开始执行用户新增汽车结束");
        if (b) {
            return new Result(true, StatusCode.ADDED_SUCCESSFULLY, StatusMessageEnum.ADDED_SUCCESSFULLY.toString());
        }
        return new Result(false, StatusCode.ADD_FAILED, StatusMessageEnum.ADD_FAILED.toString());

    }


    //@ApiOperation用于描述接口方法，作用于方法上
    @ApiOperation(value = "用户修改默认车辆")

    @ApiImplicitParams({
            @ApiImplicitParam(name = "usercarId", value = "车辆id"
                    , example = "1", required = true, paramType = "query", dataType = "int")
    })
    @PostMapping("/ordinary/modifyDefaultByusercarId")
    public Result modifyDefaultByusercarId(Integer usercarId) {
        ServletRequestAttributes sra =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = sra.getRequest().getHeader("token");
        JwtUtil jwtUtil = new JwtUtil();
        Claims claims = jwtUtil.parseTokenOrdinary(token);
        if (claims == null) {

            return new Result(false, StatusCode.NOT_LOGGED_IN, StatusMessageEnum.NOT_LOGGED_IN.toString());
        }
        Object o = claims.get("token");
        Integer tokenUserId = Integer.valueOf(String.valueOf(o));
        if (usercarId == 0 && usercarId == null) {
            return new Result(false, StatusCode.CAN_NOT_BE_EMPTY, StatusMessageEnum.CAN_NOT_BE_EMPTY.toString());
        }
        log.info("开始执行用户修改默认车辆");
        boolean b = usercarService.modifyDefaultByusercarId(usercarId);
        log.info("开始执行用户修改默认车辆结束");
        return b == true ? new Result(true, StatusCode.CAN_NOT_BE_EMPTY, StatusMessageEnum.SUCCESSFULLY_MODIFIED.toString())
                : new Result(false, StatusCode.FAIL_TO_EDIT, StatusMessageEnum.FAIL_TO_EDIT.toString());
    }


    /*
     * 功能描述〈修改车辆信息〉
     * @author:zjq
     * @param:
     * @return:
     * @Date 2021/4/12 10:00
     * @throws
     */

    @ApiOperation(value = "用户修改修改车辆信息")
    @PostMapping("/ordinary/modifyUsercarByusercarId")
    public Result modifyUsercarByusercarId(@ApiParam UsercarDto usercarDto) {
        ServletRequestAttributes sra =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = sra.getRequest().getHeader("token");
        JwtUtil jwtUtil = new JwtUtil();
        Claims claims = jwtUtil.parseTokenOrdinary(token);
        if (claims == null) {

            return new Result(false, StatusCode.NOT_LOGGED_IN, StatusMessageEnum.NOT_LOGGED_IN.toString());
        }
        Object o = claims.get("token");
        Integer tokenUserId = Integer.valueOf(String.valueOf(o));

        if (ObjectUtil.isNull(usercarDto)) {
            return new Result(false, StatusCode.CAN_NOT_BE_EMPTY, StatusMessageEnum.CAN_NOT_BE_EMPTY.toString());
        }
        log.info("开始执行修改车辆信息");
        Usercar one = CopyUtil.getOne(usercarDto, Usercar.class);
        one.setUserId(tokenUserId);
        boolean b = usercarService.modifyUsercarByusercarId(one);
        log.info("开始执行修改车辆信息结束");
        return b == true ? new Result(true, StatusCode.CAN_NOT_BE_EMPTY, StatusMessageEnum.SUCCESSFULLY_MODIFIED.toString())
                : new Result(false, StatusCode.FAIL_TO_EDIT, StatusMessageEnum.FAIL_TO_EDIT.toString());
    }

    /*
     * 功能描述〈删除〉
     * @author:zjq
     * @param:
     * @return:
     * @Date 2021/4/12 10:00
     * @throws
     */

    @ApiOperation(value = "用户删除车辆信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "usercarId", value = "车辆id"
                    , example = "1", required = true, paramType = "query", dataType = "int")
    })
    @PostMapping("/ordinary/deleteUsercarByusercarId")

    public Result deleteUsercarByusercarId(Integer usercarId) {
        ServletRequestAttributes sra =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = sra.getRequest().getHeader("token");
        JwtUtil jwtUtil = new JwtUtil();
        Claims claims = jwtUtil.parseTokenOrdinary(token);
        if (claims == null) {

            return new Result(false, StatusCode.NOT_LOGGED_IN, StatusMessageEnum.NOT_LOGGED_IN.toString());
        }
        Object o = claims.get("token");
        Integer tokenUserId = Integer.valueOf(String.valueOf(o));
        if (ObjectUtil.isNull(usercarId) && usercarId == 0) {
            return new Result(false, StatusCode.CAN_NOT_BE_EMPTY, StatusMessageEnum.CAN_NOT_BE_EMPTY.toString());
        }
        log.info("开始执行删除车辆信息");
        boolean b = usercarService.deleteUsercarByusercarId(usercarId);
        log.info("开始执行删除车辆信息结束");
        return b == true ?
                new Result(true, StatusCode.CAN_NOT_BE_EMPTY, StatusMessageEnum.SUCCESSFULLY_DELETED.toString())
                : new Result(false, StatusCode.FAILED_TO_DELETE, StatusMessageEnum.FAILED_TO_DELETE.toString());

    }


    /*
     * 功能描述〈车险信息查看根据用户id token解析用户id〉
     * @author:zjq
     * @param:
     * @return:
     * @Date 2021/4/11 23:13
     * @throws
     */
    @ApiOperation(value = "车险信息查看根据用户")
    @GetMapping("/ordinary/findCarinsuranceByUserId")
    public Result findCarinsuranceByUserId() {
        ServletRequestAttributes sra =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = sra.getRequest().getHeader("token");
        JwtUtil jwtUtil = new JwtUtil();
        Claims claims = jwtUtil.parseTokenOrdinary(token);
        if (claims == null) {

            return new Result(false, StatusCode.ERROR, StatusMessageEnum.NOT_LOGGED_IN.toString());
        }
        Object o = claims.get("token");
        Integer tokenUserId = Integer.valueOf(String.valueOf(o));

        if (tokenUserId == null && tokenUserId == 0) {

            return new Result(false, StatusCode.ERROR, StatusMessageEnum.CAN_NOT_BE_EMPTY.toString());
        }
        Carinsurance carinsuranceByUserId = carinsuranceService.findCarinsuranceByUserId(tokenUserId);
        if (ObjectUtil.isNull(carinsuranceByUserId)) {
            return new Result(false, StatusCode.ERROR, StatusMessageEnum.QUERY_IS_EMPTY.toString());
        }

        CarinsuranceDto one = CopyUtil.getOne(carinsuranceByUserId, CarinsuranceDto.class);

        return new Result(true, StatusCode.OK, StatusMessageEnum.SEARCH_SUCCESSFUL.toString(), one);
    }

    /*
     * 功能描述〈车险信息修改〉
     * @author:zjq
     * @param:
     * @return:
     * @Date 2021/4/11 23:08
     * @throws
     */
    @ApiOperation(value = "车险信息修改")
    @PostMapping("/ordinary/modifyCarinsuranceByUserId")
    public Result modifyCarinsuranceByUserId(@ApiParam CarinsuranceParam carinsuranceParam) {
        ServletRequestAttributes sra =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = sra.getRequest().getHeader("token");
        JwtUtil jwtUtil = new JwtUtil();
        Claims claims = jwtUtil.parseTokenOrdinary(token);
        if (claims == null) {

            return new Result(false, StatusCode.ERROR, StatusMessageEnum.NOT_LOGGED_IN.toString());
        }
        Object o = claims.get("token");
        Integer tokenUserId = Integer.valueOf(String.valueOf(o));
        if (ObjectUtil.isNull(carinsuranceParam)) {
            return new Result(false, StatusCode.CAN_NOT_BE_EMPTY, StatusMessageEnum.CAN_NOT_BE_EMPTY.toString());

        }
        Carinsurance one = CopyUtil.getOne(carinsuranceParam, Carinsurance.class);
        one.setUserId(tokenUserId);
        Boolean aBoolean = carinsuranceService.modifyCarinsuranceByUserId(one);
        return aBoolean ?
                new Result(true, StatusCode.SUCCESSFULLY_MODIFIED, StatusMessageEnum.SUCCESSFULLY_MODIFIED.toString())
                : new Result(false, StatusCode.FAIL_TO_EDIT, StatusMessageEnum.FAIL_TO_EDIT.toString());


    }

    /*
     * 功能描述〈查询汽车品牌〉
     * @author:zjq
     * @param:
     * @return:
     * @Date 2021/4/10 17:05
     * @throws
     */
    @ApiOperation(value = "查询汽车品牌（解析token获取）")
    @GetMapping("/ordinary/findCarbrand")
    public Result findCarbrand() {
        ServletRequestAttributes sra =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = sra.getRequest().getHeader("token");
        JwtUtil jwtUtil = new JwtUtil();
        Claims claims = jwtUtil.parseTokenOrdinary(token);
        if (claims == null) {

            return new Result(false, StatusCode.ERROR, StatusMessageEnum.NOT_LOGGED_IN.toString());
        }

        List<Carbrand> carbrand = carbrandService.findCarbrand();
        if (ObjectUtil.isNull(carbrand)) {
            return new Result(false, StatusCode.ERROR, StatusMessageEnum.QUERY_IS_EMPTY.toString());
        }

        List<CarbrandDto> carbrandList = CopyUtil.getList(carbrand, CarbrandDto.class);

        return new Result(true, StatusCode.OK, StatusMessageEnum.SEARCH_SUCCESSFUL.toString(), carbrandList);
    }

    /*
     * 功能描述〈查询汽车型号〉
     * @author:zjq
     * @param:
     * @return:
     * @Date 2021/4/10 17:35
     * @throws
     */
    @ApiOperation(value = "查询汽车型号（解析token获取）")
    @GetMapping("/ordinary/findCarmodel")
    public Result findCarmodel() {
        ServletRequestAttributes sra =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = sra.getRequest().getHeader("token");
        JwtUtil jwtUtil = new JwtUtil();
        Claims claims = jwtUtil.parseTokenOrdinary(token);
        if (claims == null) {

            return new Result(false, StatusCode.ERROR, StatusMessageEnum.NOT_LOGGED_IN.toString());
        }
        List<Carmodel> carmodel = carmodelService.findCarmodel();
        if (ObjectUtil.isNull(carmodel)) {
            return new Result(false, StatusCode.ERROR, StatusMessageEnum.QUERY_IS_EMPTY.toString());
        }

        List<CarmodelDto> carmodelList = CopyUtil.getList(carmodel, CarmodelDto.class);

        return new Result(true, StatusCode.OK, StatusMessageEnum.SEARCH_SUCCESSFUL.toString(), carmodelList);
    }


    /*
     * 功能描述〈查询所有汽车排量〉
     * @author:zjq
     * @param:
     * @return:
     * @Date 2021/4/10 19:56
     * @throws
     */
    @ApiOperation(value = "查询查询所有汽车排量")
    @GetMapping("/ordinary/findCardisplacement")
    public Result findCardisplacement() {
        ServletRequestAttributes sra =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = sra.getRequest().getHeader("token");
        JwtUtil jwtUtil = new JwtUtil();
        Claims claims = jwtUtil.parseTokenOrdinary(token);
        if (claims == null) {

            return new Result(false, StatusCode.ERROR, StatusMessageEnum.NOT_LOGGED_IN.toString());
        }
        List<Cardisplacement> cardisplacement = cardisplacementService.findCardisplacement();
        if (ObjectUtil.isNull(cardisplacement)) {
            return new Result(false, StatusCode.ERROR, StatusMessageEnum.QUERY_IS_EMPTY.toString());
        }

        List<CardisplacementDto> cardisplacementList = CopyUtil.getList(cardisplacement, CardisplacementDto.class);

        return new Result(true, StatusCode.OK, StatusMessageEnum.SEARCH_SUCCESSFUL.toString(), cardisplacementList);

    }


    /*
     * 功能描述〈查询所有汽车年份〉
     * @author:zjq
     * @param:
     * @return:
     * @Date 2021/4/11 22:27
     * @throws
     */

    @ApiOperation(value = "查询所有汽车年份")
    @GetMapping("/ordinary/findCaryears")
    public Result findCaryears() {
        ServletRequestAttributes sra =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String token = sra.getRequest().getHeader("token");
        JwtUtil jwtUtil = new JwtUtil();
        Claims claims = jwtUtil.parseTokenOrdinary(token);
        if (claims == null) {

            return new Result(false, StatusCode.ERROR, StatusMessageEnum.NOT_LOGGED_IN.toString());
        }
        List<Caryears> caryears = caryearsService.findCaryears();
        if (ObjectUtil.isNull(caryears)) {
            return new Result(false, StatusCode.ERROR, StatusMessageEnum.QUERY_IS_EMPTY.toString());
        }

        List<CaryearsDto> caryearsList = CopyUtil.getList(caryears, CaryearsDto.class);

        return new Result(true, StatusCode.OK, StatusMessageEnum.SEARCH_SUCCESSFUL.toString(), caryearsList);

    }


}